<?php
include_once('../includes/definer.php');
include_once(INC.'php/bootstrap.php');

if ($_POST['id']) {
    $publicacion = Doctrine::getTable('publicacion')->find($_POST['id']);
    Doctrine_Query::create()->delete('Tagging')->where('id_publicacion = ?', $_POST['id'])->execute();
} else {
    $publicacion = new Publicacion();
}

//INFO
if (isset($_POST['titulo'])) $publicacion->titulo = $_POST['titulo'];
if (isset($_POST['categoria'])) $publicacion->id_categoria = $_POST['categoria'];
if (isset($_POST['estado'])) $publicacion->id_estado = $_POST['estado'];
if (isset($_POST['contenido'])) $publicacion->contenido = $_POST['contenido'];
if (isset($_POST['fecha'])) $publicacion->publicado = preg_replace ('/([0-9]{2})-([0-9]{2})-([0-9]{4})/', '$3-$2-$1 00:00:00', $_POST['fecha']);

//tags
if (isset($_POST['tags'])) {
    $tags = explode('|', $_POST['tags']);
    foreach ($tags as $value) {
        if (!$value) continue;
        if (!$tag = Doctrine::getTable('tag')->findOneByValue($value)) {
            $tag = new Tag();
            $tag->value = $value;
        }
        $publicacion->tags[] = $tag;
    }
}
$publicacion->save();

if (isset($_POST['imgprefix'])) {
    $i=  Imagen::lastId();
    
    //thumb
    foreach (glob(INC.'../content/tmp/images/thumb/thumb-'.$_POST['imgprefix'].'-*') as $img) {
        $imageName = str_replace(INC.'../content/tmp/images/thumb/', '', $img);
        $ext = explode('.', $imageName);
        $publicacion->thumb = 'thumb-'.$publicacion->slug.'.'.end($ext);
        $publicacion->save();
        //rename($img, INC.'../content/images/'.'thumb-'.$publicacion->slug.'.'.end($ext));
        //echo($img);echo('<br />'.INC.'../content/images/thumb/thumb-'.$publicacion->thumb);exit();
        rename($img, INC.'../content/images/thumb/'.$publicacion->thumb);
    }
    
    foreach (glob(INC.'../content/tmp/images/thumb/'.$_POST['imgprefix'].'-*') as $img) {
        $imageName = str_replace(INC.'../content/tmp/images/thumb/', '', $img);
        $imageModel = Doctrine::getTable('imagen')->findOneBySrc($imageName);
        $imageModel->src = $publicacion->slug.'.'.$i.'.jpg';
        $imageModel->publicacion = $publicacion;
        $imageModel->save();
        rename(INC.'../content/tmp/images/'.$imageName, INC.'../content/images/'.$publicacion->slug.'.'.$i.'.jpg');
        rename(INC.'../content/tmp/images/thumb/'.$imageName, INC.'../content/images/thumb/'.$publicacion->slug.'.'.$i.'.jpg');
        $i++;
    }
    
}



if (isset($_POST['redirect'])) {
    if ($_POST['redirect'] == 'aboutme') {
        header('location: '.URL.'about-me#success');
        exit();
    }
    if ($_POST['redirect'] == 'prensa') { 
        header('location: '.URL.'notas#success')
        ;exit();
    }
    $accion = ($_POST['id'])?'#edit':'#new';
    header('location: '.URL.'publicaciones'.$accion);
}
?>
